﻿using System;

namespace WholeSlideImageLibrary.Formats.PhilipsTiff
{
    internal class PhilipsTiffXmlMetadata
    {
        public string? Manufacturer { get; set; }
        public PhilipsTiffXmlMetadataScanedImage[]? ScanedImages { get; set; }
    }

    internal class PhilipsTiffXmlMetadataScanedImage
    {
        public string? DerivationDescription { get; set; }
        public PhilipsTiffPixelSpacing PixelSpacing { get; set; }
        public PhilipsTiffXmlMetadataImageLevel[]? RepresentationSequence { get; set; }
    }

    internal class PhilipsTiffXmlMetadataImageLevel
    {
        public PhilipsTiffPixelSpacing PixelSpacing { get; set; }
        public int Rows { get; set; }
        public int Columns { get; set; }
        public short Number { get; set; }
    }

    internal readonly struct PhilipsTiffPixelSpacing
    {
        public PhilipsTiffPixelSpacing(double x, double y)
        {
            X = x;
            Y = y;
        }

        public double X { get; }
        public double Y { get; }

        public static bool TryParse(ReadOnlySpan<char> buffer, out PhilipsTiffPixelSpacing spacing)
        {
            int pos = buffer.IndexOf(' ');
            if (pos <= 0)
            {
                spacing = default;
                return false;
            }
            ReadOnlySpan<char> data1 = buffer.Slice(0, pos);
            ReadOnlySpan<char> data2 = buffer.Slice(pos + 1);
            if (data1.Length < 3 || data2.Length < 3)
            {
                spacing = default;
                return false;
            }
            if (data1[0] != '\"' || data1[data1.Length - 1] != '\"' || data2[0] != '\"' || data2[data1.Length - 1] != '\"')
            {
                spacing = default;
                return false;
            }

            if (!DoubleTryParse(data1.Slice(1, data1.Length - 2), out double x) || !DoubleTryParse(data2.Slice(1, data2.Length - 2), out double y))
            {
                spacing = default;
                return false;
            }

            spacing = new PhilipsTiffPixelSpacing(x, y);
            return true;
        }


#if NO_FAST_SPAN
        private static bool DoubleTryParse(ReadOnlySpan<char> buffer, out double value)
        {
            return double.TryParse(buffer.ToString(), out value);
        }
#else
        private static bool DoubleTryParse(ReadOnlySpan<char> buffer, out double value)
        {
            return double.TryParse(buffer, out value);
        }
#endif
    }
}
